package com.kitty.web.client.service;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.player.model.PlayerProfile;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.service.NewTeamService;
import com.kitty.game.team.service.TeamService;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.session.SessionProperties;
import com.kitty.web.client.ClientRoleManage;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;
@Slf4j
@Service
public class AiTeamService {
    @Autowired
    TeamService teamService;
    @Autowired
    NewTeamService newTeamService;
    public void getAiJoinTeam(Role role){
        int level = role.getLevel();
        if(teamService.isTeamLeader(role)){
            int num =teamService.getTeamCount(role);
            getAiByLevel(role,level,num);
        }else{
            log.info("队员无法使用此功能添加AI。。。");
        }
    }

    public void getAiByLevel(Role role ,int level, int num){
        level = getRange(level);
        //获取所有对应等级的AI
        ConcurrentMap<Integer, IoSession> fightAiMap = ClientRoleManage.fightAiSessionMap.get(level);
        if(fightAiMap== null || fightAiMap.size() == 0){
            return ;
        }
        for (Map.Entry<Integer, IoSession> integerIoSessionEntry : fightAiMap.entrySet()) {
            int roleId = integerIoSessionEntry.getKey();
            Role aiRole = SpringUtils.getRoleService().getOnlinePlayer(roleId);
            if(aiRole != null){
                //AI是否有队伍。 没有队伍执行加入队伍 指令
               if(!teamService.isInTeam(aiRole)){
                   if(num == 5){
                       continue;
                   }
                   //申请加入队伍。
                   newTeamService.requestJoin(aiRole,role.getRoleId());
                   num +=1;
               }
            }

        }

    }
    //定时检测假人队伍，是否应该离队。
    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkAiTeam(){
        for (Map.Entry<Integer, ConcurrentMap<Integer, IoSession>> integerConcurrentMapEntry : ClientRoleManage.fightAiSessionMap.entrySet()) {
            for (Map.Entry<Integer, IoSession> integerIoSessionEntry : integerConcurrentMapEntry.getValue().entrySet()) {
                PlayerProfile attribute = (PlayerProfile)integerIoSessionEntry.getValue().getAttribute(SessionProperties.PLAYER);
                Role role = DataCache.ONLINE_ROLES.get(attribute.getGid());
                if(role != null){
                    if(teamService.isTeamLeader(role)){
                        teamService.leave(role, false);
                    }
                }
            }
        }
    }
    public int getRange(int level){
        return level/10*10;
    }
}
